package coollemon.dataBase;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import coollemon.kernel.ContactManager;

public class DataManager {
	private String fileName;
	private DatabaseControl dbc  = null;
	private boolean useDb = false;
	public boolean enableDatabase(String databseUser, String databasePassword, String database,
			String port,String tableName){
		dbc = DatabaseControl.getInstance(databseUser, databasePassword, database, port, tableName);
		useDb = true;
		return true;
	}
	
	public boolean disEnableDatabase(){
		dbc.close();
		dbc = null;
		useDb = false;
		return true;
	}
	public static DataManager dataManager = new DataManager();

	private DataManager() {
	}

	public String getFileName() {
		if (fileName == null)
			return "";
		return fileName;
	}

	public ContactManager readFile(String name) {
		int kind = DataManager.getFormat(name);
		DataFormat format = DataFormat.createDataFormat(kind);
		return format.readFile(name);
	}

	public boolean writeFile(ContactManager conM, String filename) {
		int kind = DataManager.getFormat(filename);
		DataFormat format = DataFormat.createDataFormat(kind);
		if (format.writeFile(conM, filename))
			return true;
		return false;
	}

	public static int getFormat(String filename) {
		int id = 0;
		String regex = "((xml)|(vcard)|(xlsx)|(xls)|(csv))$";
		Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(filename);
		if (!matcher.find()) {
			try {
				throw new Exception("Can't open this file");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		String str = matcher.group(1);
		if (str.equalsIgnoreCase("xml"))
			id = 1;
		else if (str.equalsIgnoreCase("vcard"))
			id = 2;
		else if (str.equalsIgnoreCase("xls"))
			id = 3;
		else if (str.equalsIgnoreCase("xlsx"))
			id = 4;
		else if (str.equalsIgnoreCase("csv"))
			id = 5;
		else
			;
		return id;
	}

	public static void main(String[] args) {

		String filename = "asda.xmldd.Xlsx.csv.xml";
		System.out.println(getFormat(filename));
	}
}